import pandas as pd
import numpy as np

from stressPrinter.Utils import DateTimeUtil


class AnkeAna():
    def __init__(self, file):
        self.srcFile = file
        self._data = {}
        self._raw_df = pd.DataFrame(columns=['sID', 'time', 'ch1', 'ch2'])
        self._init()

    @property
    def df(self):
        return self._raw_df

    @property
    def data(self):
        if not self._data:
            df = self._raw_df
            df['date'] = df['time'].apply(
                lambda x: DateTimeUtil.formatDateTimeBy(DateTimeUtil.parseDateTimeBy(x, "%Y-%m-%d %H:%M:%S"),
                                                        "%Y-%m-%d"))
            df['timestamp'] = df['time'].apply(
                lambda x: DateTimeUtil.formatTimeStamp(DateTimeUtil.parseDateTimeBy(x, "%Y-%m-%d %H:%M:%S")))
            self._data['sID'] = df.iloc[0, 0]
            for date, dfi in df.groupby('date'):
                srcData = np.zeros([3, len(dfi)], dtype='float')
                start_stamp = DateTimeUtil.formatTimeStamp(
                    DateTimeUtil.parseDateTimeBy(f"{date} 00:00:00", "%Y-%m-%d %H:%M:%S"))
                dataLen = 0
                for index, row_data in dfi.iterrows():
                    x = row_data['timestamp'] - start_stamp
                    srcData[0][dataLen] = x
                    srcData[1][dataLen] = row_data['ch1']
                    srcData[2][dataLen] = row_data['ch2']
                    dataLen += 1
                self._data[date] = srcData
        return self._data

    def _init(self):
        try:
            _df = pd.DataFrame(columns=['传感器id', '时间', '通道1', '通道2'])
            _raw_dict = pd.read_excel(self.srcFile, sheet_name=None,
                                      usecols=['传感器id', '时间', '通道1', '通道2'],
                                      dtype={'时间': 'datetime64[ns]', '传感器id': 'str'})
            for key, item in _raw_dict.items():
                _df = _df._append(item)
            _df.rename(columns={'传感器id': 'sID', '时间': 'time', '通道1': 'ch1', '通道2': 'ch2'},
                       inplace=True)
            self._raw_df = self._raw_df._append(_df)
        except ValueError:
            _df = pd.DataFrame(columns=['传感器id', '时间', '通道1-监测值', '通道2-监测值'])
            _raw_dict = pd.read_excel(self.srcFile, sheet_name=None,
                                      usecols=['传感器id', '时间', '通道1-监测值', '通道2-监测值'],
                                      dtype={'时间': 'datetime64[ns]', '传感器id': 'str'})
            for key, item in _raw_dict.items():
                _df = _df._append(item)
            _df.rename(columns={'传感器id': 'sID', '时间': 'time', '通道1-监测值': 'ch1', '通道2-监测值': 'ch2'},
                       inplace=True)
            self._raw_df = self._raw_df._append(_df)


if __name__ == '__main__':
    ana = AnkeAna(r'../Data/钻孔应力传感器-10-_20240125143622.xlsx')
    print(ana.df)
